using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Practices.Common;
using EnvDTE;
using Microsoft.Practices.RecipeFramework.Library;
using System.ComponentModel.Design;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;
using Microsoft.Practices.RecipeFramework.Extensions.CommonHelpers;

namespace Microsoft.Practices.RepositoryFactory.ValueProviders.VisualStudio
{
    /// <summary>
    /// Returns a project performing a search based on its fullname
    /// </summary>
    [ServiceDependency(typeof(IDictionaryService))]
    public class ConfigurationItemProvider : ValueProvider, IAttributesConfigurable
    {
        /// <summary/>
        public const string ProjectArgumentName = "ProjectArgumentName";
        private const string WebApplicationProjectKind = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}";

        private string projectArgumentName;

        /// <summary>
        /// Uses <see cref="DteHelper.FindItemByName"/> to search for the item specified by the "Name" attributte
        /// </summary>
        /// <param name="currentValue"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        /// <seealso cref="ValueProvider.OnBeginRecipe"/>
        /// <seealso cref="DteHelper.FindItemByName"/>
        public override bool OnBeginRecipe(object currentValue, out object newValue)
        {
            newValue = null;

            IDictionaryService dictservice = (IDictionaryService)
                ServiceHelper.GetService(this, typeof(IDictionaryService));

            Project project = dictservice.GetValue(projectArgumentName) as Project;

            if(project != null)
            {
                // Check for both web site and web project types.
                if (IsWebSiteOrWebAppProject(project))
                {
                    // If the web.config is in the project root, then we want to find it there.
                    newValue = DteHelperEx.FindItemByName(project.ProjectItems, "web.config", false);

                    // Only recurse if the web.config is not found in the root.
                    if (newValue == null)
                    {
                        try
                        {
                            newValue = DteHelperEx.FindItemByName(project.ProjectItems, "web.config", true);
                        }
                        catch
                        {
                            // do nothing
                        }
                    }
                }
                

                // If a web.config was not found then look for an app.config
                if(newValue==null)
                {
                    newValue = DteHelperEx.FindItemByName(project.ProjectItems, "app.config", false);

                    if (newValue == null)
                    {
                        newValue = DteHelperEx.FindItemByName(project.ProjectItems, "app.config", true);
                    }
                }

               
                if(newValue != null)
                {
                    return true;
                }
            }

            newValue = currentValue;
            return false;
        }

        /// <param name="currentValue"></param>
        /// <param name="newValue"></param>
        /// <returns></returns>
        /// <seealso cref="ValueProvider.OnBeforeActions"/>
        /// <seealso cref="OnBeginRecipe"/>
        public override bool OnBeforeActions(object currentValue, out object newValue)
        {
            return OnBeginRecipe(currentValue, out newValue);
        }

        public override bool OnArgumentChanged(string changedArgumentName, object changedArgumentValue, object currentValue, out object newValue)
        {
            return OnBeginRecipe(currentValue, out newValue);
        }

        /// <summary>
        /// Configures the component using the dictionary of attributes specified
        /// in the configuration file.
        /// </summary>
        /// <param name="attributes">The attributes in the configuration element.</param>
        public void Configure(System.Collections.Specialized.StringDictionary attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException("attributes");
            
            if (attributes.ContainsKey(ProjectArgumentName))
            {
                projectArgumentName = attributes[ProjectArgumentName];
            }
        }

        private static bool IsWebSiteOrWebAppProject(Project project)
        {
            return (DteHelper.IsWebProject(project) || IsWebApplicationProject(project));
        }

        private static bool IsWebApplicationProject(Project project)
        {
            Guard.ArgumentNotNull(project, "project");
            return (project.Kind == WebApplicationProjectKind);
        }

    }
}
